<template>
    <div class="knowledge-detail-container" v-if="!isPageCreationVisible">
        <!-- 头部区域 -->
        <div class="header-section">
            <div class="header-main">
                <div class="header-left">
                    <a-tooltip title="返回">
                        <a-button type="text" class="back-btn" @click="navigateBack">
                            <template #icon><HomeOutlined class="icon-btn" /></template>
                        </a-button>
                    </a-tooltip>
                    <div class="title-divider"></div>
                    <h2 class="title-text">{{ knowledgeBaseName }}</h2>
                </div>
                <div class="header-right">
                    <a-input-search
                        v-model:value="searchTerm"
                        placeholder="输入文档搜索"
                        class="search-input"
                        allow-clear
                        @search="()=>initData(searchTerm)"
                    />
                </div>
            </div>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 左侧树导航 -->
            <div class="tree-panel">
                <div class="tree-header">
                    <div>知识目录</div>
                    <div class="action-buttons">
                        <div class="action-icon">
                            <a-dropdown>
                                <FileAddOutlined class="action-icon" @click.stop />
                                <template #overlay>
                                    <a-menu>
                                        <a-menu-item key="createFolder" @click="toggleFolderCreationDialog">新建文件夹</a-menu-item>
                                    </a-menu>
                                </template>
                            </a-dropdown>
                        </div>
                    </div>
                </div>
                <a-tree
                    :tree-data="knowledgeItems"
                    v-model:selected-keys="selectedTreeNodeKeys"
                    @select="onTreeNodeSelect"
                    class="custom-tree"
                >
                    <template #title="{ dataRef }">
                        <div class="tree-node-content">
                            <div v-if="!dataRef.isEditing" class="node-title">
                                <img :src="iconFolder" v-if="dataRef.type === 'dir'" class="tree-icon" alt="文件夹"/>
                                <FileOutlined v-else-if="dataRef.type === 'page'" class="tree-icon tree-icon-page" />
                                <img :src="iconFile" v-else class="tree-icon" alt="文件"/>
                                {{ formatFileName(dataRef) }}
                            </div>
                            <a-input
                                v-else
                                v-model:value="editedNodeName"
                                @keyup.enter="confirmNodeRename(dataRef)"
                                autofocus
                            />
                        </div>
                        <div class="tree-node-actions">
                            <a-tooltip v-if="dataRef.type === 'dir'">
                                <template #title>导入</template>
                                <ImportOutlined  @click="toggleImportDialog(dataRef)" class="action-icon" />
                            </a-tooltip>
                            <a-tooltip v-if="dataRef.type === 'dir'">
                                <template #title>新增文本</template>
                                <PlusOutlined @click="addChildNode(dataRef)" class="action-icon" />
                            </a-tooltip>
                            <a-dropdown>
                                <EllipsisOutlined class="action-icon" @click.stop />
                                <template #overlay>
                                    <a-menu>
                                        <a-menu-item key="renameNode" @click="initiateNodeRename(dataRef)">重命名</a-menu-item>
                                        <a-menu-item key="deleteNode" @click="confirmNodeDeletion(dataRef)">删除</a-menu-item>
<!--                                        <a-menu-item key="import" @click="toggleImportDialog()">导入</a-menu-item>-->
                                    </a-menu>
                                </template>
                            </a-dropdown>
                        </div>
                    </template>
                </a-tree>
            </div>
            <!-- 右侧编辑区域 -->
            <detailPanel :key="detailKey" :selected-knowledge="selectedKnowledgeItem" :knowledgeId="knowledgeId" @initData="initData"
                         @showPageCreation="showPageCreation"/>
        </div>
    </div>
    <!-- 编辑器 -->
    <add-pages  v-else :knowledgeId="knowledgeId"
              @closeEditor="closeEditor" :selected-knowledge="selectedKnowledgeItem"/>
    <!-- 导入 -->
    <import-file :open="isImportDialogVisible" @cancel="closeImportDialog" @initData="initData" :knowledgeId="knowledgeId" :selected-knowledge="selectedKnowledgeItem"/>
    <!-- 添加文件夹 -->
    <add-folder :addFolderVisible="isFolderCreationDialogVisible"  @initData="initData"
                @cancel="toggleFolderCreationDialog" :knowledgeId="knowledgeId"/>
    <ai-agent @fetchSuggestedQuestions="fetchSuggestedQuestions" :questions="suggestedQuestions" :chatMessage="chatMessage" v-if="aiEnable"/>

</template>

<script setup>
import {ref,onMounted,computed} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {message, Modal} from 'ant-design-vue';
import importFile from './base-detail/components/import-file.vue';
import detailPanel from './base-detail/detail-panel.vue';
import addFolder from './base-detail/components/add-folder.vue';
import addPages from './base-detail/components/add-pages.vue';
import aiAgent from './ai-agent/ai-agent.vue'
import KnowledgeBaseDetailsApi from "@/common/api/knowledge/knowledgeBaseDetails";
import KnowledgeBaseManageApi from "@/common/api/knowledge/knowledgeBaseManage";
import {TokenUtil,Util} from  '@lowcode/jpaas-base-lib'
import iconFolder from '@/assets/img/icon-folder.svg'
import iconFile from '@/assets/img/icon-file.svg'
// 路由参数
const router = useRouter();
const route = useRoute();
const knowledgeBaseName = route.query.name;
// 从路由信息中提取 id 值 和 appId 值
const knowledgeId = route.params.id;

const knowledgeItems = ref([]);
const searchTerm = ref('');
const isImportDialogVisible = ref(false);
const isFolderCreationDialogVisible = ref(false);
const isPageCreationVisible = ref(false);
// Ai
const aiEnable = ref(false);
const suggestedQuestions = ref([])
//右边详细内容key
let detailKey = ref(Util.randomId());
const chatMessage = computed(()=>{
    let token = TokenUtil.getToken();
    return {
        url: "/api/api-knowledge/knowledge/core/knowledgeBaseManage/chatMessagesByAi",
        header:{
            'Authorization': `Bearer ${token}`,
        },
        body:{
            response_mode: "streaming",
            "inputs": {},
            "user": "admin",
            "knowledgeBaseId":knowledgeId
        }
    }
})
// 左侧树参数
const selectedTreeNodeKeys = ref([]);
const selectedKnowledgeItem = ref(null);
const editedNodeName = ref("");

const navigateBack = () => {
    // router.push({name: 'knowledge'});
    router.back();
};

// 树节点选择事件
const onTreeNodeSelect = (selectedKeys, info) => {
    const {node} = info;
    selectedTreeNodeKeys.value = [node.key];
    if(node.type === 'dir'){
        selectedKnowledgeItem.value = null;
    }else{
        selectedKnowledgeItem.value = node;
    }
    //重置KEY 用于刷新右边的文档详细页面
    detailKey = Util.randomId();
}

// 新增文件夹操作
const toggleFolderCreationDialog = () => {
    isFolderCreationDialogVisible.value = !isFolderCreationDialogVisible.value;
};
const closeEditor = () =>{
    showPageCreation();
    initData();
}
const showPageCreation = () => {
    isPageCreationVisible.value = !isPageCreationVisible.value;
};

// 在树中新增操作
const addChildNode = (data) => {
    selectedKnowledgeItem.value = data;
    showPageCreation();
};

// 重命名方法
// 修改initiateNodeRename函数
const initiateNodeRename = (node) => {
    knowledgeItems.value = setEditingStatus(knowledgeItems.value, node.id);
    editedNodeName.value = findNodeInTree(knowledgeItems.value, node.id)?.name || '';
}

// 新增设置编辑状态函数
const setEditingStatus = (items, targetId) => {
    return items.map(item => ({
        ...item,
        isEditing: item.id === targetId,
        children: item.children ? setEditingStatus(item.children, targetId) : []
    }));
};
const findNodeInTree = (items, targetId) => {
    for (const item of items) {
        if (item.id === targetId) return item;
        if (item.children) {
            const found = findNodeInTree(item.children, targetId);
            if (found) return found;
        }
    }
};

const confirmNodeRename = async (node) => {
    if (editedNodeName.value.trim()) {
        let result = await KnowledgeBaseDetailsApi.save({
            id:node.id,
            name:editedNodeName.value.trim()
        })
        if(result.success){
            await initData();
            // 新增代码：重新设置选中状态
            const updatedNode = findNodeInTree(knowledgeItems.value, node.id)
            if (updatedNode) {
                selectedKnowledgeItem.value = updatedNode
                selectedTreeNodeKeys.value = [node.id]
            }
        }
    }
};

// 删除操作
const findFirstValidNode = (nodes) => {
    for (const node of nodes) {
        if (node.children?.length > 0) {
            return findFirstValidNode(node.children);
        }
        return node;
    }
    return null;
}
const updateSelection = (wasSelected) => {
    if (!wasSelected) return;

    if (knowledgeItems.value.length > 0) {
        const firstNode = findFirstValidNode(knowledgeItems.value);
        selectedTreeNodeKeys.value = firstNode ? [firstNode.id] : [];
        selectedKnowledgeItem.value = firstNode || null;
    } else {
        selectedTreeNodeKeys.value = [];
        selectedKnowledgeItem.value = null;
    }
};

const confirmNodeDeletion = (node) => {
    const id = node.id;
    let content = `您确定需要删除文档【${node.name}】吗？`;
    if (node.type==="dir") {
        content = `您确定需要删除文件夹【${node.name}】及其文档吗？`;
    }
    if (id) {
        Modal.confirm({
            title: '确认删除',
            content: content,
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
                const result = await KnowledgeBaseDetailsApi.del({ids:id});
                if(result.success) {
                    const wasSelected = selectedTreeNodeKeys.value.includes(id);
                    await initData();
                    updateSelection(wasSelected);
                }
            },
        });
    } else {
        message.warning('未找到对应的文档');
    }
};

// 导入操作
const toggleImportDialog = (data) => {
    selectedKnowledgeItem.value = data;
    isImportDialogVisible.value = !isImportDialogVisible.value;
};


const closeImportDialog = () => {
    isImportDialogVisible.value = false;
};

const initData = async(name = "",id = knowledgeId) =>{
    const result = await KnowledgeBaseDetailsApi.queryList({
        "params": {
            Q_KNOWLEDGE_ID__S_EQ: id,
            Q_NAME__S_LK:name
        }
    });
    knowledgeItems.value = transformTreeData(result.data || []);
}
const enableAi = async ()=>{
    const currentData = await KnowledgeBaseManageApi.get(knowledgeId);
    aiEnable.value = currentData.data?.enableAi;
}
const transformTreeData = (data) => {
    return Util.listToTree(
        data.map(item => ({ ...item, key: item.id })),
        "id",
        "parentId"
    );
};
// AI建议问题
const fetchSuggestedQuestions = async (messageId) => {
    try {
        // 添加重试机制
        let retries = 3;
        while (retries > 0) {
            let token = TokenUtil.getToken();
            const response = await fetch(
                `/api/api-knowledge/knowledge/core/knowledgeBaseManage/suggested/${messageId}?knowledgeBaseId=${knowledgeId}`,
                {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                }
            )
            if (response.status === 404 && retries > 0) {
                // 等待1秒后重试
                await new Promise(resolve => setTimeout(resolve, 1000));
                retries--;
                continue;
            }

            if (!response.ok) throw new Error('请求失败');

            let result = await response.json();
            suggestedQuestions.value = result || []; // 添加空值保护
            break;
        }
    } catch (error) {
        suggestedQuestions.value = [];
        console.error('获取建议失败:', error);
    }
}
// 新增名称格式化方法
const formatFileName = (dataRef) => {
    let name = dataRef.name || '';
    if(dataRef.type !== 'file'){
        return name
    }else{
        // 移除扩展名（仅对文件类型）
        const lastDotIndex = name.lastIndexOf('.');
        if (lastDotIndex > 0) {
            name = name.substring(0, lastDotIndex);
        }
        // 处理以点结尾的情况（仅当文件名以点结尾时）
        return name.endsWith('.') ? name.slice(0, -1) : name;
    }
};
onMounted(()=>{
    initData();
    enableAi()
})
</script>

<style scoped lang="scss">
@import "./base-detail/style/knowledge-basedetail";
</style>
